package com.roger.tool.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostUtils {

	private static final String TAG = HttpPostUtils.class.getSimpleName();

	public static void httpPostDataForThread(final String pUrl, final String pPostContent, final IOnHttpPostListener pOnHttpPostListener) {
		Thread thread = new Thread() {

			public void run() {
				String httpPostResult = HttpPostUtils.httpPostData(pUrl, pPostContent);
				if (pOnHttpPostListener != null) {
					pOnHttpPostListener.onHttpPostResult(httpPostResult);
				}
			}

		};
		thread.setName("httpPostData");
		thread.start();
	}

	public static String httpPostData(String pUrl, String pPostContent) {
		String httpPostResult = "";
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(pUrl).openConnection();
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			byte[] postData = pPostContent.getBytes();
			httpURLConnection.setRequestProperty("Content-length", Integer.toString(postData.length));
			httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(postData);
			outputStream.close();
			int responseCode = httpURLConnection.getResponseCode();
//			Debug.v(TAG, "responseCode:" + responseCode);
			if (200 == responseCode) {
				StringBuffer postResultBuffer = new StringBuffer();
				BufferedReader postResultBufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
				String line;
				while ((line = postResultBufferedReader.readLine()) != null) {
					postResultBuffer.append(line).append("\n");
				}
				postResultBufferedReader.close();
				httpPostResult = postResultBuffer.toString();
//				Debug.v(TAG, "httpPostResult:" + httpPostResult);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpPostResult;
	}

	public interface IOnHttpPostListener {

		public void onHttpPostResult(String pHttpPostResult);

	}
}
